package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.PlanManage;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  日程添加
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/4/19 14:59
 */
public class PlanManageAddFragment extends BaseFragment {

  protected static final String EXTRA_VALUE =
      PlanManageAddActivity.class.getSimpleName() + "EXTRA_VALUE";

  private final int SAVE = 0;
  private final int SAVE_SUB = 1;

  @BindView(R.id.et_plantitle) EditText etPlantitle;
  @BindView(R.id.tv_excname) TextView tvExcname;
  @BindView(R.id.tv_projectname) TextView tvProjectname;
  @BindView(R.id.tv_planStartTime) TextView tvPlanStartTime;
  @BindView(R.id.et_planContentDesc) EditText etPlanContentDesc;
  @BindView(R.id.tv_planEndTime) TextView tvPlanEndTime;
  @BindView(R.id.tv_corname) TextView tvCorname;
  @BindView(R.id.tv_taskvisibility) TextView tvTaskvisibility;
  @BindView(R.id.tv_filepath) TextView tvFilepath;
  @BindView(R.id.cb_remindTime) CheckBox cbRemindTime;
  @BindView(R.id.cb_remindAllPerson) CheckBox cbRemindAllPerson;
  @BindView(R.id.tv_remindTime) TextView tvRemindTime;
  @BindView(R.id.cb_setRepeatCycle) CheckBox cbSetRepeatCycle;
  @BindView(R.id.tv_repeatCycle) TextView tvRepeatCycle;
  @BindView(R.id.tv_deadline) TextView tvDeadline;
  @BindView(R.id.tv_dataStatus) TextView tvDataStatus;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;

  private final int REQUEST_EXC = 0;
  private static final int REQUEST_PROJECT = 1;
  private static final int REQUEST_STARTTIME = 2;
  private static final int REQUEST_ENDTIME = 3;
  private static final int REQUEST_COR = 4;
  private static final int REQUEST_VISIBILITY = 5;
  private static final int REQUEST_FILE = 6;
  private static final int REQUEST_REMINDTIME = 7;
  private static final int REQUEST_DEADTIME = 8;
  private static final int REQUEST_CYCLE = 9;
  private static final int REQUEST_UPLOAD = 10;
  private String mId;
  private String excjobno;
  private String projectName;
  private String projectCode;
  private String corName;
  private String corJob;
  private String visiCode;
  private String filepath;
  private CurrentUser mUser;
  private String excdeptname;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.planManage);
    mId = UUID.randomUUID().toString();
    mUser = CurrentUser.newInstance(getActivity());
    excjobno = mUser.getJobNumber();
    excdeptname = mUser.getDeptName();
    projectName = "";
    projectCode = "";
    corName = "";
    corJob = "";
    visiCode = "01";
    filepath = "";
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setVisible(false);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isComplete()) {
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        //volleyPostSave(SAVE_SUB);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private boolean isComplete() {
    if (TextUtils.isEmpty(etPlantitle.getText().toString())
        || TextUtils.isEmpty(tvExcname.getText().toString())
        || TextUtils.isEmpty(tvPlanStartTime.getText().toString())
        || TextUtils.isEmpty(tvPlanEndTime.getText().toString())
        || TextUtils.isEmpty(tvTaskvisibility.getText().toString())
        || (cbRemindTime.isChecked() && TextUtils.isEmpty(tvRemindTime.getText().toString()))) {
      ToastUtil.show(R.string.complete_hint);
      return false;
    } else {
      return true;
    }
  }

  private void volleyPostSave(int type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_MANAGE_ADD);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("excjobno", excjobno);
    params.put("excname", tvExcname.getText().toString());
    params.put("excdeptname", excdeptname);
    params.put("corjobno", corJob);
    params.put("corname", corName);
    params.put("plantitle", etPlantitle.getText().toString());
    params.put("planContentDesc", etPlanContentDesc.getText().toString());
    params.put("filepath", filepath);
    params.put("planStartTime", tvPlanStartTime.getText().toString());
    params.put("planEndTime", tvPlanEndTime.getText().toString());
    params.put("projectid", projectCode);
    params.put("projectname", projectName);
    params.put("taskvisibility", visiCode);
    params.put("dataStatus", "new");
    if (cbRemindAllPerson.isChecked()) {
      params.put("tipAllFlag", "TT");
    } else {
      params.put("tipAllFlag", "FF");
    }
    params.put("tiptime", tvRemindTime.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse(type));
  }

  private void volleyPostSubmit() {
    String url = ApiConst.getAbsoluteUrl("");
    HashMap<String, String> params = new HashMap<>();
    params.put("", "");
    mActivity.volleyPost(url, params, getResponse(SAVE));
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_plan_manage, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {

    cbRemindTime.setChecked(false);
    tvExcname.setText(mUser.getRealName());
    tvTaskvisibility.setText("公开可见");
    tvDataStatus.setText(R.string.draft);
    tvRegStaffName.setText(CurrentUser.newInstance(getActivity()).getRealName());
    tvRegDate.setText(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));

    cbRemindTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
        if (isCheck) {
          tvRemindTime.setHint(R.string.mustChoose);
        } else {
          tvRemindTime.setHint("");
          tvRemindTime.setText("");
        }
      }
    });
  }

  public VolleyResponse getResponse(final int type) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          switch (type) {
            case SAVE:
              ToastUtil.show(message.getMessage());
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
              break;
            case SAVE_SUB:
              volleyPostSubmit();
              break;
            default:
              break;
          }
        } else if (message != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        } else {
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  public static PlanManageAddFragment newInstance(PlanManage content) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, content);
    PlanManageAddFragment fragment = new PlanManageAddFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @OnClick({
      R.id.tv_excname, R.id.tv_projectname, R.id.tv_planStartTime, R.id.tv_planEndTime,
      R.id.tv_corname, R.id.tv_taskvisibility, R.id.tv_filepath, R.id.tv_remindTime,
      R.id.tv_repeatCycle, R.id.tv_deadline
  }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_excname:
        //负责人:单选
        Intent exc = new Intent(getActivity(), SearchPersonActivity.class);
        exc.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(exc, REQUEST_EXC);
        break;
      case R.id.tv_projectname:
        //相关项目
        Intent project = new Intent(getActivity(), ProjectChooseListActivity.class);
        startActivityForResult(project, REQUEST_PROJECT);
        break;
      case R.id.tv_planStartTime:
        //开始时间
        showDialog(REQUEST_STARTTIME);
        break;
      case R.id.tv_planEndTime:
        //结束时间
        showDialog(REQUEST_ENDTIME);
        break;
      case R.id.tv_corname:
        //参与人
        Intent cor = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        cor.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        startActivityForResult(cor, REQUEST_COR);
        break;
      case R.id.tv_taskvisibility:
        //可见范围
        showDialog(REQUEST_VISIBILITY);
        break;
      case R.id.tv_filepath:
        //附件上传
        //showDialog(REQUEST_FILE);
        chooseFile(REQUEST_FILE);
        break;
      case R.id.tv_remindTime:
        //提醒时间
        if (cbRemindTime.isChecked()) {
          showDialog(REQUEST_REMINDTIME);
        } else {
          ToastUtil.show("请先勾选设置提醒时间!");
        }
        break;
      case R.id.tv_repeatCycle:
        //重复周期
        showDialog(REQUEST_CYCLE);
        break;
      case R.id.tv_deadline:
        //截止至
        showDialog(REQUEST_DEADTIME);
        break;
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private void showDialog(int recuestCode) {
    DialogFragment dialogFragment = null;
    switch (recuestCode) {
      case REQUEST_STARTTIME:
        //开始时间
        dialogFragment = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_ENDTIME:
        //结束时间
        dialogFragment = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_VISIBILITY:
        //可见范围
        dialogFragment = new VisibilityDialogFragment();
        break;
      case REQUEST_FILE:
        //附件
        dialogFragment =
            ExtraUpLoadDialogFragment.newInstance("", ExtraUpLoadDialogFragment.TYPE_ALL);
        break;
      case REQUEST_REMINDTIME:
        //提醒时间
        dialogFragment = BaseTimeDialogFragment.newInstance(new Date());
        break;
      case REQUEST_CYCLE:
        //重复周期
        dialogFragment = new RepeatCycleDialogFragment();
        break;
      case REQUEST_DEADTIME:
        //截止时间
        dialogFragment = new BaseYMDTimeDialogFragment();
        break;
      default:
        break;
    }
    FragmentManager fm = getFragmentManager();
    dialogFragment.setTargetFragment(PlanManageAddFragment.this, recuestCode);
    dialogFragment.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_EXC) {
      CustomerDialog exc =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      excjobno = exc.getJobNo();
      excjobno = exc.getJobNo();
      excdeptname = exc.getDept();
      tvExcname.setText(exc.getName());
    }
    if (requestCode == REQUEST_PROJECT) {
      ProjectCollectOriginal.ProjectCollectContent objectContent =
          (ProjectCollectOriginal.ProjectCollectContent) data.getSerializableExtra(
              ProjectChooseListFragment.EXTRA_CONTENT);
      projectName = objectContent.getProjectName();
      projectCode = objectContent.getId();
      tvProjectname.setText(projectName);
    }
    if (requestCode == REQUEST_STARTTIME) {
      Date start = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String startTime = MyDateUtil.format(start, MyDateUtil.TYPE_DATE);
      tvPlanStartTime.setText(startTime);
    }
    if (requestCode == REQUEST_ENDTIME) {
      Date end = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String endTime = MyDateUtil.format(end, MyDateUtil.TYPE_DATE);
      tvPlanEndTime.setText(endTime);
    }
    if (requestCode == REQUEST_COR) {
      corName = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      corJob = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      tvCorname.setText(corName);
    }
    if (requestCode == REQUEST_VISIBILITY) {
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(VisibilityDialogFragment.EXTRA_CONTENT);
      String visiName = content.getName();
      visiCode = content.getId();
      tvTaskvisibility.setText(visiName);
    }
    if (requestCode == REQUEST_FILE) {
      //附件选择上传
      FileUploadDialgFragment dialog =
          FileUploadDialgFragment.newInstance(getFile(data), mId, "plancp.r_plan_manager_other",
              true);
      dialog.setTargetFragment(this, REQUEST_UPLOAD);
      dialog.show(mActivity.getSupportFragmentManager(), "");
    }
    if (requestCode == REQUEST_UPLOAD) {
      //附件上传成功
      filepath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      tvFilepath.setText(FileUtil.getFileNameByFilePath(filepath));
    }
    if (requestCode == REQUEST_REMINDTIME) {
      Date remind = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String remindTime = MyDateUtil.format(remind, MyDateUtil.TYPE_ALL);
      tvRemindTime.setText(remindTime);
    }

    if (requestCode == REQUEST_CYCLE) {
      CustomerDialog cycle =
          (CustomerDialog) data.getSerializableExtra(RepeatCycleDialogFragment.EXTRA_CONTENT);
      String cycleName = cycle.getName();
      //String cycleCode = cycle.getId();
      tvRepeatCycle.setText(cycleName);
    }
    if (requestCode == REQUEST_DEADTIME) {
      Date dead = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String deadTime = MyDateUtil.format(dead, MyDateUtil.TYPE_DATE);
      tvDeadline.setText(deadTime);
    }
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }
}
